package com.service.Authorization.task;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.Authorization.dto.SsidConfigDto;
import com.service.Authorization.dto.SsidDto;
import com.service.Authorization.entity.PortalUser;
import com.service.Authorization.service.PortalUserService;
import com.service.config.constant.ApiUrlConstants;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.service.config.constant.ApiUrlConstants.URL_FIRST;


@Slf4j
@Service
public class ScheduledService {
    @Resource
    RedisUtil redisUtil;
    @Resource
    RestTemplate restTemplate;
    @Resource
    private PortalUserService portalUserService;

    public static ExecutorService product = Executors.newFixedThreadPool(10);

    public void scheduled1(String manageId,List<PortalUser> portalUserList,int i) throws Exception {
        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        List<SsidDto> ssidDtoList = new ArrayList<>();
        //获取token
        portalUserList.forEach(portalUser -> {
            List<SsidDto> sites = new ArrayList<>();
            HttpHeaders token = getToken(portalUser.getTenantName(), portalUser.getTenantPwd(), portalUser.getDomain(), requestHeaders);
            if (token != null) {
                sites = getSites(token, portalUser.getDomain());
            }
            if (sites != null) {
                List<SsidDto> ssidDtos = new ArrayList<>();
                sites.forEach(ssidDto ->{
                    HashMap map = new HashMap();
                    map.put("ids", Arrays.asList(ssidDto.getId()));
                    HttpEntity<Map> requestEntity = new HttpEntity<>(map, requestHeaders);
                    ResponseEntity<JSONObject> response = restTemplate.exchange(
                            URL_FIRST.concat(portalUser.getDomain()).concat(ApiUrlConstants.SS_ID_DEL_URL).concat(ssidDto.getSiteId()).concat("/apssid") , HttpMethod.GET, requestEntity, JSONObject.class);
                    JSONObject responseBody = response.getBody();
                    if ("0".equals(responseBody.getString("errcode"))) {
                        //List<SsidConfigDto> data1 = ModelMapperUtil.strictMapList(responseBody.getJSONArray("data"), SsidConfigDto.class);
                        JSONArray data = response.getBody().getJSONArray("data");
                        if (!data.isEmpty()) {
                            List<SsidConfigDto> ssidConfigDtos = data.toJavaList(SsidConfigDto.class);
                            ssidConfigDtos.forEach(ssidConfigDto -> {
                                if (ssidConfigDto.getSsidAuth()!= null) {
                                    if (ssidConfigDto.getSsidAuth().getPortal() != null) {
                                        if (ssidConfigDto.getSsidAuth().getPortal().getMode() != null && ssidConfigDto.getSsidAuth().getPortal().getMode().equals("portalThirdIndirect")) {
                                            ssidDto.setId(ssidConfigDto.getId());
                                            ssidDto.setName(ssidConfigDto.getName());
                                            ssidDto.setTenantName(portalUser.getTenantName());
                                            ssidDto.setTenantPwd(portalUser.getTenantPwd());
                                            ssidDto.setPortalUserId(portalUser.getId());
                                            ssidDto.setManageId(manageId);
                                            ssidDto.setDomain(portalUser.getDomain());
                                            ssidDtos.add(ssidDto);
                                        }
                                    }
                                }
                            });
                        }
                    }
                });
                ssidDtoList.addAll(ssidDtos);
            }
        });
        if (ssidDtoList.size() > 0) {
            List<SsidDto> ssidDtoList1 = new ArrayList<>();
            Map<String, List<SsidDto>> collect = ssidDtoList.stream().collect(Collectors.groupingBy(SsidDto::getId));
            collect.forEach((key, value) -> ssidDtoList1.add(value.get(0)));
            if (redisUtil.exist(manageId.concat(":ssidDto"))) {
                if (i == 0) {
                    redisUtil.delete(manageId.concat(":ssidDto"));
                }
            }
            for (SsidDto ssidDto : ssidDtoList1){
                try {
                    redisUtil.leftPush(manageId.concat(":ssidDto"), JsonXMLUtils.obj2json(ssidDto));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 获取站点信息
     * @param requestHeaders
     * @return
     */
    private List<SsidDto> getSites(HttpHeaders requestHeaders,String domain) {
        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.exchange(URL_FIRST.concat(domain).concat(ApiUrlConstants.SITE_URL) , HttpMethod.GET, requestEntity, JSONObject.class);
            JSONArray jsonResponse = response.getBody().getJSONArray("data");
            List<SsidDto> list = new ArrayList();
            for (int i = 0; i < jsonResponse.size(); i++) {
                SsidDto ssidDto = new SsidDto();
                String id = jsonResponse.getJSONObject(i).getString("id");
                ssidDto.setSiteId(id);
                list.add(ssidDto);
            }
            return list;
        }catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取token_id
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public HttpHeaders getToken(String username, String password,String domain, HttpHeaders requestHeaders) {
        String token = "";
        if (redisUtil.exist(username.concat("token"))) {
            token = redisUtil.getValue(username.concat("token"));
            requestHeaders.add("X-AUTH-TOKEN", token);
            requestHeaders.add("Accept-Language", "en-US");
            return requestHeaders ;
        } else {
            try {
                Map map = new HashMap();
                map.put("userName", username);
                map.put("password", password);
                HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_FIRST.concat(domain).concat(ApiUrlConstants.CLOUD_CAMPUS_TOKEN_URL), requestEntity, JSONObject.class);
                JSONObject jsonObject = response.getBody().getJSONObject("data");
                token = jsonObject.get("token_id").toString();
                redisUtil.set(username.concat("token"),1,token,10);
                requestHeaders.add("X-AUTH-TOKEN",token);
                requestHeaders.add("Accept-Language", "en-US");
                return requestHeaders;
            }catch (Exception e) {
                return null ;
            }

        }
    }
   // @Scheduled(cron = "0 0 */1 * * ?")
    //@Scheduled(fixedDelay = 2000)
    @Async("taskExecutor")
    public void getLoginUserDispose() throws Exception {
        List<PortalUser> portalUserList = portalUserService.queryAllS(new PortalUser());
        if (portalUserList.size() > 0) {
            Map<String, List<PortalUser>> collect = portalUserList.stream().collect(Collectors.groupingBy(PortalUser::getManageId));
            collect.forEach((key, value) -> {
                product.submit(()->{
                    try {
                        scheduled1(key,value,0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            });
        }
    }
    @Async("taskExecutor")
    public void getLoginUserDispose(PortalUser screenUser,int i) throws Exception {
        List<PortalUser> portalUserList = new ArrayList<>();
        portalUserList.add(screenUser);
        try {
            scheduled1(screenUser.getManageId(),portalUserList,i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


